package wsz.rocketMq.conf;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import wsz.rocketMq.dao.OrderDao;
import wsz.rocketMq.entity.Order;
import wsz.rocketMq.util.Constants;

import java.sql.Timestamp;
import java.util.List;

/**
 * 定时扫描订单状态
 * @author wsz
 * @date 2022/3/2 11:18
 **/
@Slf4j
@Component
public class OrderSchedule {

    @Autowired
    private OrderDao orderDao;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Scheduled(cron = "*/2 * * * * ?")
    public void scanOrderStatus() {
        // 1.未付款且订单创建时间已超过2分钟
        Timestamp timestamp = new Timestamp(System.currentTimeMillis() - 1000*60*2);
        List<Order> orderList = orderDao.findUnPay(Constants.PAY_NO, timestamp);
        if (CollectionUtils.isEmpty(orderList)) return;
        log.info("库存还原：{}", orderList.size());
        // 2.库存复位
        Timestamp outTime = new Timestamp(System.currentTimeMillis());
        orderList.forEach(order -> {
            order.setStatus(Constants.PAY_TIMEOUT);
            order.setOutTime(outTime);
        });
        // TODO-存在未全部更新的情况
        List<Order> saveAll = orderDao.saveAll(orderList);
        // 进行库存还原
        redisTemplate.opsForValue().increment(Constants.KILL_PHONE_KEY, saveAll.size());
    }
}
